using Microsoft.AspNetCore.Mvc;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Request.Ai;
using WCS.Service.Interface;

namespace WCS.Api.Admin.Controllers
{
    /// <summary>
    /// 文件说明：AI 对话中转控制器
    /// 作用：封装后端中转混元 chat/completions 的 Web API
    /// 作者：系统自动生成
    /// 日期：2025-11-19
    /// </summary>
    public class AiController : BaseController
    {
        private readonly IConfiguration _configuration;
        private readonly IHunyuanService _hunyuanService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration">配置读取器</param>
        /// <param name="hunyuanService">混元服务</param>
        /// <param name="userService">用户服务（基类依赖）</param>
        public AiController(IConfiguration configuration, IHunyuanService hunyuanService, IUserService userService) : base(userService)
        {
            _configuration = configuration;
            _hunyuanService = hunyuanService;
        }

        /// <summary>
        /// AI 对话（后端中转混元 chat/completions）
        /// </summary>
        /// <param name="dto">对话请求参数</param>
        /// <returns>统一返回对象，code==0 表示成功</returns>
        /// <exception cref="System.Exception">网络或解析错误由异常中间件统一处理</exception>
        [HttpPost]
        [ActionLog(Action = "对话", Group = "AI模块")]
        public async Task<IActionResult> Chat([FromBody] ChatRequestDto dto)
        {
            var result = await _hunyuanService.ChatAsync(dto);
            return Ok(result);
        }

        /// <summary>
        /// AI 对话（流式输出，SSE），OpenAI 兼容参数 stream=true
        /// </summary>
        /// <param name="dto">对话请求参数，建议包含 stream=true</param>
        /// <returns>空结果；SSE 数据直接写入响应流</returns>
        /// <exception cref="System.Exception">网络或复制流异常由中间件统一处理</exception>
        [HttpPost]
        [Produces("text/event-stream")]
        [ActionLog(Action = "流式对话", Group = "AI模块")]
        public async Task<IActionResult> ChatStream([FromBody] ChatRequestDto dto)
        {
            Response.StatusCode = StatusCodes.Status200OK;
            Response.ContentType = "text/event-stream";
            Response.Headers["Cache-Control"] = "no-cache";
            Response.Headers["X-Accel-Buffering"] = "no";

            var cts = HttpContext.RequestAborted;
            var resp = await _hunyuanService.ChatStreamRawAsync(dto, cts);

            await using var input = await resp.Content.ReadAsStreamAsync(cts);
            var buffer = new byte[8192];
            int read;
            while ((read = await input.ReadAsync(buffer.AsMemory(0, buffer.Length), cts)) > 0)
            {
                await Response.Body.WriteAsync(buffer.AsMemory(0, read), cts);
                await Response.Body.FlushAsync(cts);
            }

            return new EmptyResult();
        }
    }
}
